<?php

require_once('post_controller.php');
require_once('category_controller.php');
require_once('../models/authorization.php');
require_once('../includes/smarty/libs/Smarty.class.php');
require_once('../models/comment.php');

class ViewController{
	
	private $smarty;
	private $post_controller;
	private $session;

	public function ViewController(){
		
		$this->smarty = new Smarty();
		$this->post_controller = new PostController();
		$this->session = new Authorization();
		
		$type = $_GET['type'];

		if ($type == "category")
			$this->renderCategoryView();
		if ($type == "article")
			$this->renderArticleView();
			
		if(isset($_POST['commentor_name']))
			$this->addComment();
			
		$this->renderPage();
	}
	
	private function addComment(){
		
		Comment::add($_POST['commentor_name'], $_POST['comment_text'], $_POST['comment_post_id']);
		header("Location: view.php?type=article&id=" . $_POST['comment_post_id']);
	}
	
	const COMMENTS_PLACEHOLDER_NAME = "comments";
	
	private function renderArticleView(){
		
		$post_id = $_GET['id'];
		$p = $this->post_controller->getPostById($post_id);
	
		$post_array = array();
		array_push($post_array, array("title" => $p->getTitle(),
							 	  "author" => $p->getAuthor(),
						     	  "date" => $p->getPostDate(),
						     	  "message" => $p->getEntry(),
							 	  "id" => $p->getId(),
							 	  "category" => $p->getCategoryName(),
							 	  "comments" => $p->commentsAllowed()));
	
		$this->smarty->assign("posts", $post_array);
		$this->smarty->assign("title", $p->getTitle());
		$this->smarty->assign("loggedIn", $this->session->checkLogin());
		
		// render an articles comments if it has any
		$comments = Comment::findArticleComments($p->getId());
		if($comments > 0){
			
			$comments_array = array();
			
			foreach ($comments as $c){
				array_push($comments_array, array("id" => $c->getId(),
										 		  "author" => $c->getAuthor(),
									 			  "text" => $c->getComment(),
									 			  "date" => $c->getSubmitDate()));
			}
			$this->smarty->assign(self::COMMENTS_PLACEHOLDER_NAME, $comments_array);			
		}
	}
	
	private function renderCategoryView(){
		
  		$category_id = $_GET['id'];
  
  		$c = new CategoryController();
  		$p = $this->post_controller->getPostsByCategory($category_id);
  		
  		$this->smarty->assign("posts", $p);
  		$this->smarty->assign("title", $c->getCategoryNameById($category_id));
		$this->smarty->assign("loggedIn", $this->session->checkLogin());
	}
	
	const TEMPLATE_NAME = "view.tpl";
	
	private function renderPage(){
		
		$this->smarty->display('view.tpl');
	}
}
$viewController = new ViewController();
?>
